//
//  UserViewController.m
//  Tang
//
//  Created by 邓芮 on 15/12/3.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "UserViewController.h"
#import "CoreDataMan.h"
#import "MyLikeCell.h"
#import "MyLikeSectionCell.h"
#import "VideoPlayerController.h"
#import "RecommendDetailController.h"
#import "SKUDetailController.h"
#import "AppDelegate.h"
#import "UserSetViewController.h"
#import <BmobSDK/BmobProFile.h>
#import <BmobSDK/BmobFile.h>
typedef NS_ENUM(NSInteger , rightBtnState)
{
    ediButtonDelete,
    ediButtonCancel
};

static NSString *cellIdentifier = @"cell";
@interface UserViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    CGFloat BackGroupHeight;
    CGFloat HeadImageHeight;
    rightBtnState rightButtonState;
    BOOL _isBackground;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) UIImageView *headerImage;
@property (nonatomic, strong) UILabel *name;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UILabel *waringLabel;//空白提醒;

@property (nonatomic, strong) NSMutableArray *playArray;//播放数组
@property (nonatomic, strong) NSMutableArray *everyArray;//每日一晒
@property (nonatomic, strong) NSMutableArray *skuArray;//单品的数组
//@property (nonatomic, strong) UILabel *hintLable;//如果没有的时候提示信息
@end


static NSString *headerCell = @"header";
static NSString *cellInden = @"cell";
@implementation UserViewController
{
    BmobFile *headerFile;
    
    BmobFile *backgroundFile;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    self.navigationController.navigationBar.translucent = YES;

    [self initView];
    
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser)
    {
       self.name.text = bUser.username;
    }
    
    BmobQuery *query = [BmobQuery queryWithClassName:@"_User"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        for (BmobObject *object in array)
        {
            if ([self.name.text isEqualToString:[object objectForKey:@"username"]])
            {
                 headerFile = [object objectForKey:@"headerImage"];
                [self.headerImage sd_setImageWithURL:[NSURL URLWithString:headerFile.url]placeholderImage:[UIImage imageNamed:@"happy"]];
                backgroundFile = [object objectForKey:@"backgroundImage"];
                [self.backImageView sd_setImageWithURL:[NSURL URLWithString:backgroundFile.url] placeholderImage:[UIImage imageNamed:@"background"]];
            }
            
        }
    }];
    
    self.playArray =[NSMutableArray arrayWithArray:[[CoreDataMan shareIntance]allPlay]];
    self.everyArray = [NSMutableArray arrayWithArray:[[CoreDataMan shareIntance]allEvery]];
    self.skuArray = [NSMutableArray arrayWithArray:[[CoreDataMan shareIntance]allSku]];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    label.center = CGPointMake(self.tableView.center.x, 100*KHeight / 568);
    label.text = @"空空如也!快去收藏一些吧!";
    self.waringLabel = label;
    [self.tableView addSubview:label];
    if (self.skuArray.count == 0 &&self.everyArray.count == 0 && self.playArray.count ==0)
    {
        label.hidden = NO;
        self.tableView.scrollEnabled = NO;
        
    }
    else
    {
        label.hidden = YES;
        self.tableView.scrollEnabled =YES;
    }


    
}

- (void)initView
{
    BackGroupHeight = 400 * KWidth / 414;
    HeadImageHeight = 80 * KWidth / 414;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KHeight)style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(BackGroupHeight, 0, 0, 0);
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
    
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MyLikeCell class] forCellReuseIdentifier:cellInden];
    [self.tableView registerClass:[MyLikeSectionCell class] forHeaderFooterViewReuseIdentifier:headerCell];
    
    
    self.backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -BackGroupHeight, KWidth, BackGroupHeight)];
    UITapGestureRecognizer *backTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeBackImage:)];
    self.backImageView.userInteractionEnabled = YES;
    [self.backImageView addGestureRecognizer:backTap];
    self.backImageView.image = [UIImage imageNamed:@"background"];
    
    [self.tableView addSubview:self.backImageView];
    
    self.headerImage = [[UIImageView alloc]initWithFrame:CGRectMake((KWidth - HeadImageHeight)/2, -180 * KWidth / 414, HeadImageHeight, HeadImageHeight)];
    self.headerImage.userInteractionEnabled = YES;
    self.headerImage.layer.cornerRadius = HeadImageHeight / 2;
    self.headerImage.layer.masksToBounds = YES;
//    self.headerImage.image = [UIImage imageNamed:@"happy"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeHeaderImage:)];
    [self.headerImage addGestureRecognizer:tap];
    
//    [self.headerView addSubview:self.headerImage];
    [self.tableView addSubview:self.headerImage];
    
    
    
    self.name = [[UILabel alloc]initWithFrame:CGRectMake((KWidth - HeadImageHeight) / 2, CGRectGetMaxY(self.headerImage.frame), HeadImageHeight, 20)];
    self.name.textColor = [UIColor whiteColor];
    self.name.textAlignment = NSTextAlignmentCenter;
//    self.name.text = @"Ally";
//    [self.headerView addSubview:self.name];
    [self.tableView addSubview:self.name];
    

//    self.titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
//    self.titleLabel.textColor=[UIColor whiteColor];
//    self.titleLabel.text=@"title";
//    
//    self.titleLabel.textAlignment=NSTextAlignmentCenter;
//    
//    self.navigationItem.titleView=self.titleLabel;
//    self.titleLabel.alpha=0;
    
    UIButton *leftBtn=[UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBtn.frame = CGRectMake(0, 0, 25, 25);
    [leftBtn setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [leftBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem=leftItem;
    
    UIButton *rightBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 30)];
    [rightBtn setTitle:@"退出" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
    self.navigationItem.rightBarButtonItem=rightItem;
    self.rightButton = rightBtn;
    rightButtonState = ediButtonCancel;
    
    
    
    }
#pragma mark  --编辑tableView------

- (void)rightBtnAction
{
//    UserSetViewController *userSetViewVc = [[UserSetViewController alloc]init];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要退出?一旦退出收藏的内容将清空~" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [BmobUser logout];
        self.navigationController.navigationBar.translucent = NO;
        [self.navigationController popToRootViewControllerAnimated:YES];
        
        // 退出时删除所有数据
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
             [[CoreDataMan shareIntance] deleteAllEvery];
        [[CoreDataMan shareIntance] deleteAllPlay];
        [[CoreDataMan shareIntance] deleteAllSku];
        });
       
    }];
    UIAlertAction *dissmiss = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:sure];
    [alert addAction:dissmiss];
    [self presentViewController:alert animated:NO completion:nil];
//    [self.navigationController pushViewController:userSetViewVc animated:NO];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        Sku *aSku = self.skuArray[indexPath.row];
        [[CoreDataMan shareIntance]deleteSkuWithId:aSku.p_j_id];
        [self.skuArray removeObjectAtIndex:indexPath.row];
        
        
    }
    else if (indexPath.section == 1)
    {
        Every *aEvery = self.everyArray[indexPath.row];
        [[CoreDataMan shareIntance]deleteEveryWithId:aEvery.p_j_id];
        [self.everyArray removeObjectAtIndex:indexPath.row];
        
    }
    else if (indexPath.section == 2)
    {
        Play *aPlay = self.playArray[indexPath.row];
        [[CoreDataMan shareIntance] deletePlayWithId:aPlay.playUrl];
        [self.playArray removeObjectAtIndex:indexPath.row];
        
    }
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    if (self.skuArray.count == 0 &&self.everyArray.count == 0 && self.playArray.count ==0)
    {
        [self.tableView setContentOffset:CGPointMake(0, -BackGroupHeight) animated:YES];
        self.waringLabel.hidden = NO;
        self.tableView.scrollEnabled = NO;
        
    }
    else
    {
        self.waringLabel.hidden = YES;
        self.tableView.scrollEnabled =YES;
    }

    [self.tableView reloadData];
}

- (void)changeBackImage:(UITapGestureRecognizer *)tap
{
    _isBackground = YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改背景" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"获取系统相机");
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            //摄像头
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        }
        //如果没有系统相机提示用户
        else
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"您的设备没有摄像" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alert addAction:sure];
            [self presentViewController:alert animated:NO completion:nil];
        }

        
        
    }];
    UIAlertAction *openAlbum  = [UIAlertAction actionWithTitle:@"从相册上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"打开系统相册");
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;//是否可以编辑
            //打开相册选择照片
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            // 模态进入相册
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:takePhoto];
    [alert addAction:openAlbum];
    [alert addAction:cancel];
    [self presentViewController:alert animated:NO completion:nil];


}

#pragma mark -- 拍摄完成后或者选择相册完成后自动调用的方法 --
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if (_isBackground)
    {
        //得到图片
        self.backImageView.image = [info objectForKey:UIImagePickerControllerEditedImage] ;
        self.backImageView.image = [self imageWithImage:self.backImageView.image scaledToSize:CGSizeMake(320, 320)];
        [self selectImageToSqliteImage:self.backImageView.image name:@"backgroundImage"];
    }
    else
    {
        self.headerImage.image = [info objectForKey:UIImagePickerControllerEditedImage];
        self.headerImage.image = [self imageWithImage:self.headerImage.image scaledToSize:CGSizeMake(100, 100)];
        [self selectImageToSqliteImage:self.headerImage.image name:@"headerImage"];
    }

    // 模态返回
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)changeHeaderImage:(UITapGestureRecognizer *)tap
{
    _isBackground = NO;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"获取系统相机");
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;//是否可以编辑
            //打开相册选择照片
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            // 模态进入相册
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *openAlbum  = [UIAlertAction actionWithTitle:@"从相册上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"打开系统相册");
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;//是否可以编辑
            //打开相册选择照片
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            // 模态进入相册
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:takePhoto];
    [alert addAction:openAlbum];
    [alert addAction:cancel];
    [self presentViewController:alert animated:NO completion:nil];
}

- (void)backAction:(UIButton *)btn
{
     self.navigationController.navigationBar.translucent = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return self.skuArray.count;
    }
    else if (section == 1)
    {
        return self.everyArray.count;
        
    }
    else if (section == 2)
    {
        return self.playArray.count;
    }
    else
    {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyLikeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInden forIndexPath:indexPath];
    if (indexPath.section == 0)
    {
        Sku *aSku = self.skuArray[indexPath.row];
        [cell setContentWithNsstring:aSku.title imageUrl:aSku.imageUrl width:[aSku.width integerValue] height:[aSku.height integerValue]];
    }
    else if (indexPath.section == 1)
    {
        Every *aEvery = self.everyArray[indexPath.row];
        [cell setContentWithNsstring:aEvery.title imageUrl:aEvery.imagUrl width:[aEvery.width integerValue] height:[aEvery.height integerValue]];
    }
    else if (indexPath.section == 2)
    {
        Play *aPlay = self.playArray[indexPath.row];
        [cell setContentWithNsstring:aPlay.title imageUrl:aPlay.imagUrl width:[aPlay.width integerValue] height:[aPlay.height integerValue]];
    }
    return cell;

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MyLikeSectionCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerCell];
    if (section == 0)
    {
        cell.titleLabel.text = @"精选收藏";
    }
    else if (section == 1)
    {
        cell.titleLabel.text = @"晒晒收藏";
    }
    else if (section == 2)
    {
        cell.titleLabel.text = @"美妆视频";
    }
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        if (self.skuArray.count == 0)
        {
            return 0;
        }
        else
        {
            return 30;
        }

        
    }
    else if (section == 1)
    {
        if (self.everyArray.count == 0)
        {
            return 0;
        }
        else
        {
            return 30;
        }

        
    }
    else if (section == 2)
    {
        if (self.playArray.count == 0)
        {
            return 0;
        }
        else
        {
            return 30;
        }

    }
    else
    {
        return 0;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        Sku *aSku = self.skuArray[indexPath.row];
       return  [MyLikeCell heightForRowWithString:aSku.title width:[aSku.width integerValue] height:[aSku.height integerValue]];
    }
    else if (indexPath.section == 1)
    {
        Every *aEvery = self.everyArray[indexPath.row];
      return   [MyLikeCell heightForRowWithString:aEvery.title width:[aEvery.width integerValue] height:[aEvery.height integerValue]];
    }
    else if (indexPath.section == 2)
    {
        Play *aPlay = self.playArray[indexPath.row];
      return  [MyLikeCell heightForRowWithString:aPlay.title width:[aPlay.width integerValue] height:[aPlay.height integerValue]];
    }
    else
    {
        return 0;
    }
    
}

#pragma mark  --- 点击跳转---
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        Sku *aSku = self.skuArray[indexPath.row];
        SKUDetailController *skuVc = [[SKUDetailController alloc] init];
        skuVc.ID = aSku.p_j_id;
        [self.navigationController pushViewController:skuVc animated:YES];
    }
    else if (indexPath.section == 1)
    {
        Every *aEvery = self.everyArray[indexPath.row];
        RecommendDetailController *recommendVc = [[RecommendDetailController alloc] init];
        recommendVc.Id = aEvery.p_j_id;
        
        [self.navigationController pushViewController:recommendVc animated:YES];
        
    
    }
    else if (indexPath.section == 2)
    {
        Play *aPlay = self.playArray[indexPath.row];
        VideoPlayerController  *videoVc = [[VideoPlayerController alloc] init];
        AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
        appDelegate.isRotation = YES;
        videoVc.url = aPlay.playUrl;
        videoVc.name = aPlay.title;
        [self presentViewController:videoVc animated:YES completion:nil];
    }

}



#pragma mark -- 图片下拉放大 --
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset  = scrollView.contentOffset.y;
    CGFloat xOffset = (yOffset + BackGroupHeight)/2;
    
    if (yOffset < -BackGroupHeight) {
        
        CGRect rect = self.backImageView.frame;
        rect.origin.y = yOffset;
        rect.size.height =  -yOffset ;
        rect.origin.x = xOffset;
        rect.size.width = KWidth + fabs(xOffset)*2;
        
        self.backImageView.frame = rect;
    }
    else
    {
        if  (yOffset <= 0)
            
        {
            CGFloat y = fabs(yOffset) ;
            self.tableView.contentInset = UIEdgeInsetsMake(y, 0, 0, 0);
            self.navigationController.navigationBar.translucent = YES;
//            self.tableView.height = KHeight;
            
            
            
        }
        
    }
    if (yOffset >= 0)
    {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.navigationController.navigationBar.translucent = NO;
   
        self.tableView.height = KHeight - 64;

        
        
    }

    
    
    CGFloat alpha = (yOffset+BackGroupHeight)/BackGroupHeight;
    if (alpha >= 0.5)
    {
        UIButton *btn = (UIButton *)self.navigationItem.leftBarButtonItem.customView;
        [btn setTitleColor:[[UIColor blackColor] colorWithAlphaComponent:alpha] forState:UIControlStateNormal];
        UIButton *right = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        [right setTitleColor:[[UIColor orangeColor] colorWithAlphaComponent:alpha] forState:UIControlStateNormal];
        //self.navigationController.navigationBar.translucent = NO;
    }
    else
    {
        UIButton *btn = (UIButton *)self.navigationItem.leftBarButtonItem.customView;
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        UIButton *right = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        [right setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        self.titleLabel.textColor = [UIColor orangeColor];

    }
   
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor whiteColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
    self.titleLabel.alpha=alpha;
    alpha=fabs(alpha);
    alpha=fabs(1-alpha);
    
    alpha=alpha<0.2? 0:alpha-0.2;

    
    // BGView.alpha=alpha;
    
    
}

#pragma mark -- 改变图片的颜色 --
- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}

#pragma mark --在相册中选中的图片添加到数据库中--
-(void)selectImageToSqliteImage:(UIImage *)image name:(NSString *)name{
    
    //图片的名字不能重复命名 所有根据当前时间来命名图片
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [date timeIntervalSince1970]*1000;
    NSString *nowTime = [NSString stringWithFormat:@"%f",a];
    //转换成data类型
    NSData *imageData = UIImagePNGRepresentation(image);
    //获得documents路径
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    //拼接文件名字 不能重名
    NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"image%@.jpg",nowTime]];
    //将图片写入到上面的文件内
    [imageData writeToFile:fullPathToFile atomically:NO];
    //拼接获取图片文件的路径
    NSString  *filePath = [NSString stringWithFormat:@"%@/image%@.jpg",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"],nowTime];
    //NSLog(@"filePath ==%@",filePath);
    //上传图片
    [BmobProFile uploadFileWithPath:filePath block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
        if (isSuccessful) {
            //返回文件名和url
            BmobUser *user = [BmobUser getCurrentUser];
            BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:@"_User"  objectId:user.objectId];
            [bmobObject setObject:file forKey:name];
            [bmobObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful) {
                    //修改成功后的动作
                    //NSLog(@"进度完成,修改图片成功");
                    self.view.userInteractionEnabled = YES;
                    [self.tableView reloadData];
                    
                } else if (error){
                    NSLog(@"%@",error);
                } else {
                    NSLog(@"UnKnow error");
                }
            }];
        }
        
    } progress:^(CGFloat progress) {
        NSLog(@"%lf",progress);
    }];
    
}

#pragma mark--压缩图片封装方法
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
